package com.imyuanma.qingyun.common.util;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

/**
 * xml工具类
 *
 * @author wangjiyu
 * @date 2021/10/5 18:31
 */
public class XmlUtil {

    /**
     * 对象转xml字符串
     * @param object
     * @return
     */
    public static String beanToXml(Object object) {
        XStream xstream = new XStream(new DomDriver());
        xstream.autodetectAnnotations(true);
        return xstream.toXML(object);
    }

    /**
     * xml字符串转bean
     * @param xml
     * @param <T>
     * @return
     */
    public static <T> T xmlToBean(String xml, Class<T> clz) {
        XStream xstream = new XStream(new DomDriver());
        XStream.setupDefaultSecurity(xstream);
        xstream.allowTypes(new Class[]{clz});
        xstream.autodetectAnnotations(true);
        xstream.processAnnotations(clz);
        return (T) xstream.fromXML(xml);
    }
}
